<template>
  <div class="upload-box">
    <label :for="inputId">
      <slot />
    </label>
    <input
      :id="inputId"
      class="upload-file-btn hidden"
      ref="inputRef"
      type="file"
      :accept="acceptStr"
      @change="onChange"
    >
  </div>
</template>

<script>
import { ref } from 'vue';
import { Toast } from 'vant';
import { useService } from '@/utils/services';
export default {
  emits: ['update:modelValue', 'success'],
  props: {
    accept: {
      type: String,
      default: 'image/*'
    },
    modelValue: {
      type: Array,
      default: () => []
    }
  },
  setup(props, { emit }) {
    const acceptStr = ref(props.accept);
    const inputRef = ref(null);

    const inputId = `upload-file-${(Math.random() * 100).toString(16).slice(8)}`;

    const actions = useService();

    function onChange(e) {
      const [file] = e.target.files;
      upload(file);
    }

    function checkFileSize(file) {
      const MAX_KB = 200 * 1024;
      let kb = file.size / 1024;

      if (kb > MAX_KB) {
        Toast('文件最大上传 200M');
        return false;
      }

      return true;
    }

    function upload(file) {
      const toast = Toast.loading({
        duration: 0,
        message: '发送中',
        loadingType: 'spinner'
      });
      const formData = new FormData();
      if (!checkFileSize(file)) return;
      formData.append('file', file);
      actions.hos
        .uploadFile(formData)
        .then((res) => {
          emit('success', res);
        })
        .catch(() => {})
        .finally(() => {
          toast.clear();
        });
    }

    return {
      inputRef,
      inputId,
      acceptStr,
      onChange
    };
  }
};
</script>

<style lang="scss" scoped>
</style>